package com.example.pets.view.activity;

import android.net.Uri;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.LogoPosition;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.SupportMapFragment;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.example.pets.MapApplication;
import com.example.pets.R;
import com.example.pets.model.entities.Post;
import com.example.pets.model.entities.User;
import com.example.pets.model.entities.database.AppDatabase;
import com.example.pets.model.entities.database.ShareprefenseUtil;
import com.example.pets.view.fragment.adapter.ImageAdapter;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PostActivity extends AppCompatActivity implements OnGetGeoCoderResultListener {

    private EditText etAuthorId, etContent;
    private Button btnSubmit;
     ImageAdapter imageAdapter;
    List<String> selectedImages;
    RecyclerView rvImagePreview;
    private FragmentManager manager;
    public SupportMapFragment mSupportMapFragment;
    private BaiduMap mBaiduMap;
    private MapView mMapView;
    private static final double EARTH_RADIUS = 6378137;
    private GeoCoder mGeoCoder;
    private BitmapDescriptor bitmap;
    private TextView tv_adr;
    private String address;
    private LatLng mLatLng;
    private RadioGroup radioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        etAuthorId = findViewById(R.id.et_author_id);
        etContent = findViewById(R.id.et_content);
        btnSubmit = findViewById(R.id.btn_submit);
        tv_adr = findViewById(R.id.tv_adr);
         radioGroup = findViewById(R.id.radio_group_type);
        tv_adr.setText("当前地址："+MapApplication.location.getCity()+MapApplication.location.getDistrict()+MapApplication.location.getStreet());
        // 在onCreate方法内添加如下代码：
        selectedImages = new ArrayList<>();
        rvImagePreview = findViewById(R.id.rv_image_preview);
        rvImagePreview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        imageAdapter = new ImageAdapter(this, selectedImages);
        rvImagePreview.setAdapter(imageAdapter);

        findViewById(R.id.btn_add_image).setOnClickListener(v -> {
            PictureSelector.create(PostActivity.this)
                    .openGallery(SelectMimeType.ofImage()).setMaxSelectNum(5)
                    .setImageEngine(new YImageEngine()) // 使用Glide加载图片
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            for (LocalMedia media : result) {
                                selectedImages.add(media.getAvailablePath() != null ? Uri.parse(media.getAvailablePath()).getPath() : Uri.fromFile(new File(media.getPath())).toString());
                                imageAdapter.notifyDataSetChanged();
                            }


                        }

                        @Override
                        public void onCancel() {
                            // 取消选择
                        }
                    });
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String authorId = etAuthorId.getText().toString();
                String content = etContent.getText().toString();

                if (authorId.isEmpty() || content.isEmpty()) {
                    Toast.makeText(PostActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                User user = ShareprefenseUtil.getinstanse().getLoginUser();
                Post post = new Post();
                post.setTitle(authorId);
                post.setContent(content);
                post.setImageUrls(selectedImages); // 示例，实际应用中应根据需要调整
                post.setLikesCount(0);
                post.setCommentsCount(0);
                post.setLatitude(mLatLng.latitude);
                post.setLongitude(mLatLng.longitude);
                post.setAdress(address);
                post.setAuthorurl(user.getImageUrl());
                post.setAuthorname(user.getUname());
                int selectedId = radioGroup.getCheckedRadioButtonId();

                if (selectedId == R.id.rb_missing) {
                  post.setIslost(true);;
                } else if (selectedId == R.id.rb_dynamic) {
                    post.setIslost(false);
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        AppDatabase db = AppDatabase.getDatabase(getApplicationContext());
                        long ids = db.postDao().insert(post);
                        if(ids>0){
                            finish();
                        }

                    }
                }).start();



            }
        });


        mMapView = (MapView) findViewById(R.id.bmapView);

         mLatLng = new LatLng(MapApplication.location.getLatitude(), MapApplication.location.getLongitude());

        //北京为地图中心，logo在左上角
        MapStatusUpdate status1 = MapStatusUpdateFactory.newLatLng(mLatLng);
        MapStatus mapStatus = new MapStatus.Builder()
                .target(mLatLng)
                .zoom(15)
                .build();
        mBaiduMap= mMapView.getMap();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus));

        mMapView.getMap().setMapStatus(status1);
        mMapView.setLogoPosition(LogoPosition.logoPostionleftTop);

        addMarker(mLatLng, "当前位置");

        // 创建地理编码检索实例
        mGeoCoder = GeoCoder.newInstance();
        mGeoCoder.setOnGetGeoCodeResultListener(this);

        // 准备 Marker 图标
        bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.marker_icon);

        // 添加地图点击监听器
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            // 普通点击
            @Override
            public void onMapClick(LatLng point) {
                mLatLng =point;
                addMarker(point,"");
                getAddress(point);
            }

            // POI 点击不触发
            @Override
            public void onMapPoiClick(MapPoi poi) {

            }
        });
    }



    // 根据经纬度获取地址信息
    private void getAddress(LatLng latLng) {
        // 发起反向地理编码请求
        mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                .location(latLng));
    }
    // 添加标记点的方法
    private void addMarker(LatLng latLng, String title) {
        mBaiduMap.clear();
        // 定义 Marker 图标（可自定义）
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.marker_icon);

        // 构建 MarkerOption 对象
        OverlayOptions options = new MarkerOptions()
                .position(latLng)
                .icon(bitmap)
                .title(title)
                .draggable(false); // 是否可拖拽

        // 添加到地图中
        mBaiduMap.addOverlay(options);
    }

    // 可选：设置 Marker 点击监听器
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();

        mBaiduMap.setOnMarkerClickListener(marker -> {
            String title = marker.getTitle();
            // 显示 Toast 或弹窗
            Toast.makeText(this, "你点击了：" + title, Toast.LENGTH_SHORT).show();
            return true; // 表示已消费点击事件
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }
    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        if (result == null || result.error != com.baidu.mapapi.search.core.SearchResult.ERRORNO.NO_ERROR) {
            // 没有检测到结果
            System.out.println("未找到结果");
            return;
        }

        // 获取详细的地址信息
         address = result.getAddress();
        System.out.println("地址: " + address);
        tv_adr.setText("当前地址："+address);


        // 显示地址信息
//        showInfoWindow(result.getLocation(), address);
    }

    // 显示 InfoWindow
    private void showInfoWindow(LatLng latLng, String address) {
        // 创建 InfoWindow 显示的内容
        InfoWindow infoWindow = new InfoWindow(BitmapDescriptorFactory.fromResource(R.mipmap.marker_icon),
                latLng, -47, new InfoWindow.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick() {
                // 点击 InfoWindow 后的操作
                mBaiduMap.hideInfoWindow();
            }
        });

        // 自定义 InfoWindow 内容
        // 这里可以创建一个自定义的 View 并设置为 InfoWindow 的内容
        // 注意：这里只是简单打印地址，你可以根据需要进一步定制 InfoWindow 的样式

        // 显示 InfoWindow
        mBaiduMap.showInfoWindow(infoWindow);
    }
}